package com.limingru.newbee.api;

import com.limingru.newbee.api.param.GoodsSearchParam;
import com.limingru.newbee.api.vo.GoodsDetailVO;
import com.limingru.newbee.common.Constants;
import com.limingru.newbee.common.NewBeeMallException;
import com.limingru.newbee.service.GoodsService;
import com.limingru.newbee.util.Result;
import com.limingru.newbee.util.ResultGenerator;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/v1")
public class GoodsAPI {

    @Resource
    GoodsService goodsService;

    @PostMapping("/search")
    public Result searchGoods(@RequestBody @Valid GoodsSearchParam goodsSearchParam) {
        Long goodsCategoryId = goodsSearchParam.getGoodsCategoryId();
        String keywords = goodsSearchParam.getKeywords();
        Integer pageNumber = goodsSearchParam.getPageNumber();
        Integer pageSize = goodsSearchParam.getPageSize();
        String orderBy = goodsSearchParam.getOrderBy();
        Map params = new HashMap<>(5);
        if (goodsCategoryId == null && StringUtils.isEmpty(keywords)) {
            NewBeeMallException.fail("非法的搜索参数");
        }
        if (pageNumber == null || pageNumber < 1) {
            pageNumber = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        if (StringUtils.isEmpty(orderBy)) {
            orderBy = Constants.GOODS_SEARCH_ORDER_BY_DEFAULT;
        }
        int start = (pageNumber - 1) * 10;
        params.put("goodsCategoryId", goodsCategoryId);
        params.put("keywords", keywords);
        params.put("pageNumber", pageNumber);
        params.put("start", start);
        params.put("pageSize", pageSize);
        params.put("goodsSellStatus", Constants.GOODS_SELL_STATUS_UP);
        params.put("orderBy", orderBy);
        System.out.println(params);

        return ResultGenerator.generateSuccessResult(goodsService.search(params));
    }

    @GetMapping("/goods/{goodsId}")
    public Result<GoodsDetailVO> goodsDetail(@PathVariable("goodsId") Long goodsId) {
        GoodsDetailVO goodsDetailVO = goodsService.detail(goodsId);
        return ResultGenerator.generateSuccessResult(goodsDetailVO);
    }
}
